/**
 * Http 请求封装
 */

const config = require('./config.js')
const store = require("./store.js")
const utils = require("../utils/util.js")
const {Dialog, Notify, Toast} = require("./modal")

/** 参数  */
let Const = {
    // 默认服务端地址
    HOST: "http://127.0.0.1:8080/",
    // 空字符串检测
    ARR_NULL: [undefined, null, '', null, "undefined"],
    // 未授权可访问的服务端地址
    NO_AUTH_URLS: config.noAuthUrl,
    // http请求超时
    TIME_OUT: config.timeout
}

/** 辅助函数 */
const FUN = {
    // 读取配置初始化信息
    init: () => {
        let server = config.server;
        let activeServer = server[config.active];
        Const.HOST = activeServer.doMain
    },
    filter: (obj) => {
        if (obj != null && obj != undefined) {
            Object.keys(obj).forEach(function (key) {
                if (Const.ARR_NULL.indexOf(obj[key]) >= 0) {
                    delete obj[key];
                }
            });
        }
    },
    reqLog: (url, method, data, header) => {
        let reqMap = {};
        reqMap.url = url;
        reqMap.method = method;
        reqMap.param = data;
        reqMap.header = header;
        return reqMap;
    },
    loading: (isLoading) => {
        if (isLoading) {
            // 弹出loading
            wx.showLoading({
                title: '加载中',
                mask: true,
            })
        }
    },
    closeLoading(isLoading) {
        if (isLoading) {
            wx.hideLoading({})
        }
    },
    getDefaultHeader(method) {
        let contentType = "application/json"
        if (method == "GET" || method == "DELETE") {
            contentType = "application/x-www-form-urlencoded";
        }
        let authorization = store.getAuthorization();
        return {
            'Content-Type': contentType,
            'Authorization': authorization
        }
    }
}

FUN.init();


/**
 * post 请求
 * @param loading 请求前是否弹出loading
 * @param url 服务端接口地址
 * @param method 请求类型
 * @param data 请求参数
 * @param header 头部
 * @param callback 回调函数 Function
 */
// const http = (loading, url, method, data, header, callback) => {
//     execute(loading, true, url, method, data, header, callback)
// }

/**
 * get 请求
 * @param loading 请求前是否弹出loading
 * @param url 服务端接口地址
 * @param data 请求参数
 * @param header 头部
 * @param callback 回调函数 Function
 */
const gets = (loading, url, data, header, callback) => {
    execute(loading, true, url, 'GET', data, header, callback)
}

/**
 * post 请求
 * @param loading 请求前是否弹出loading
 * @param url 服务端接口地址
 * @param data 请求参数
 * @param header 头部
 * @param callback 回调函数 Function
 */
const post = (loading, isErrorTip, url, data, header, callback) => {
    execute(loading, isErrorTip, url, 'POST', data, header, callback)
}

/**
 * del 请求
 * @param loading 请求前是否弹出loading
 * @param url 服务端接口地址
 * @param data 请求参数
 * @param header 头部
 * @param callback 回调函数 Function
 */
const del = (loading, url, data, header, callback) => {
    execute(loading, true, url, 'DELETE', data, header, callback)
}

/**
 * put 请求
 * @param loading 请求前是否弹出loading
 * @param url 服务端接口地址
 * @param data 请求参数
 * @param header 头部
 * @param callback 回调函数 Function
 */
const put = (loading, url, data, header, callback) => {
    execute(loading, true, url, 'PUT', data, header, callback)
}
const http = (url,header,method,data,callback)=>{
    FUN.loading(true);
    wx.request({
        timeout: FUN.TIME_OUT,
        url: url,
        data: data,
        dataType: 'json',
        method: method == null ? 'GET' : method,
        header: header ,
        success(res) {
            callback(res)
        },
        complete(res) {
            setTimeout(() => {
                FUN.closeLoading(true);
            }, 100)
        },
        fail(res) {
            console.log("http error", res)
            tip("服务器罢工了～😔");
        }
    })
}
const execute = (loading, isErrorTip, url, method, data, header, callback) => {
    console.log("请求开始", Const.HOST + url)
    let noCheck = false;
    let urls = Const.NO_AUTH_URLS;
    for (const urlsKey in urls) {
        let source = urls[urlsKey].replace("/**", "");
        if (!utils.isInvalid(source)) {
            noCheck = url.indexOf(source) >= 0;
            if (noCheck) {
                break;
            }
        }
    }



    // if (!noCheck) {
    //     console.log("权限校验,收否登陆")
    //     let authorization = store.getAuthorization();
    //     if (utils.isInvalid(authorization)) {
    //         console.log("openid不存在，重新授权")
    //         wx.navigateTo({
    //             url: config.noAuthPage + "?nextPage=http",
    //         })
    //         return;
    //     }
    // }
    let reqMap = FUN.reqLog(url, method, data, header)

    // 过滤空字符串
    FUN.filter(data)

    FUN.loading(loading);

    wx.request({
        timeout: FUN.TIME_OUT,
        url: Const.HOST + url,
        data: data,
        dataType: 'json',
        method: method == null ? 'GET' : method,
        header: header == null ? FUN.getDefaultHeader(method) : header,
        success(res) {
            let statusCode = res.statusCode;
            let msg = "";
            if (statusCode === 502) {
                msg = "服务器罢工了～😔";
            } else if (statusCode == 402) {
                msg = "sorry,跑错路了～"
            } else if (statusCode == 500) {
                msg = "服务器繁忙，请重试～"
            }
            if (!utils.isInvalid(msg)) {
                tip(msg);
                return;
            }
            if (res.data[config.response.codeKey] != config.SUCCESS_CODE) {
                if (isErrorTip) {
                    Dialog.alert({
                        message: res.data[config.response.msgKey],
                        width: "250px",
                        confirmButtonColor: "#D2691E",
                        confirmButtonText: "关闭",
                    })
                }
                res.data['R'] = false
            } else {
                res.data['R'] = true
            }
            callback(res.data)
            // ------------------
            reqMap.statusCode = res.statusCode
            reqMap.response = res.data
            //console.log("响应结束", reqMap)

        },
        complete(res) {
            setTimeout(() => {
                FUN.closeLoading(loading);
            }, 100)
        },
        fail(res) {
            console.log("http error", res)
            tip("服务器罢工了～😔");
        }
    })
}

function tip(msg) {
    Dialog.alert({
        message: msg,
        width: "250px",
        confirmButtonColor: "#D2691E",
        confirmButtonText: "关闭",
    }).then(() => {
    });
}



module.exports = {
    gets: gets,
    post: post,
    del: del,
    put: put,
    http:http
}
